package com.zrc.superframe

import android.annotation.SuppressLint
import android.app.Application
import androidx.multidex.MultiDex
import com.alibaba.android.arouter.launcher.ARouter
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.zrc.superframe_aop.SuperAop
import com.zrc.superframe_base.utils.transformations.GlideLoader
import com.zrc.module_my.IConstantPool
import com.zrc.superframe_net.common.net.Net
import com.zrc.superframe_net.utils.HawkSpUtitls
import com.zrc.superframe_tbs.TbsUtils
import io.reactivex.Observable
import me.jessyan.autosize.AutoSizeConfig
import me.jessyan.autosize.unit.Subunits
import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl

/**
 * @Author: superman
 * @CreateTime: 6/27/21
 * @Describe:
 */
open class BaseApplication : Application() {

    companion object {
        lateinit var mAppContext: BaseApplication
    }

    override fun onCreate() {
        super.onCreate()
        mAppContext = this@BaseApplication
        MultiDex.install(this)
        ARouter.init(this)
        if (BuildConfig.DEBUG) {
            ARouter.openLog()
            ARouter.openDebug()
        }
        GlideLoader.getInstance().init(this)
        AutoSizeConfig//屏幕适配
            .getInstance()
            .unitsManager
            .setSupportDP(false)
            .setSupportSP(false)
            .supportSubunits = Subunits.MM

        SuperAop
            .init(this)//初始化
            .setDebug(BuildConfig.DEBUG)
            .setLog("SuperAop")//日志开关

        initNet()

        initSmartRefreshLayout()

        TbsUtils.get().init(this)
    }

    private fun initNet() {
        Net
            .init(this)//初始化网络请求
            .setDebug(true) //是否输出调试日志
            .setBaseUrl(IConstantPool.sCommonUrl)
            .setApplictionId("com.zrc.superframe")
            //以下都是按需设置
            .setDownloadsQueueCount(5) //下载最大数量
            .setDbName("net.db") //数据库名
            .setConnectionTimeout(6) //普通请求连接超时
            .setReadTimeout(6) //普通请求读取超时
            .setDownConnectionTime(6) //下载连接超时   6秒
            .setNetBufferTime(60) //有网络的情况下缓存  60秒
            .setNoNetBufferTime(24 * 60 * 60 * 7) //无网络的时候，缓存
            .setCookieJarInterceptor(object : CookieJar {
                private fun generateCookie(cookieStr: String, path: String): Cookie {
                    val builder = Cookie.Builder()
                    val split = cookieStr.split("|")
                    builder.name(split[1]).value(split[2]).domain(split[0]).httpOnly().path(path)
                    return builder.build()
                }

                override fun loadForRequest(url: HttpUrl): List<Cookie> {//网络请求前cookie设置
                    val cookies = ArrayList<Cookie>()
                    val cookiesMap = HawkSpUtitls.get("cookie1", mutableMapOf<String, String>())
                    cookiesMap.forEach {
                        cookies.add(generateCookie(it.value, it.key))
                    }
                    return cookies
                }

                @SuppressLint("CheckResult")
                override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {//拦截到cookie后做存储
                    val cookiesMap = HawkSpUtitls.get("cookie1", mutableMapOf<String, String>())
                    Observable.fromIterable(cookies)
                        .subscribe {
                            cookiesMap[it.path] = it.domain + "|" + it.name + "|" + it.value
                        }
                    HawkSpUtitls.save("cookie1", cookiesMap)
                }
            })
//            .setInterceptor {
//                val builder = with(it.request().newBuilder()) {
//                    val cookies= HawkSpUtitls.get("cookie", arrayListOf<String>())
//                    val cookiesStr=GsonUtils.toJson(cookies)
//                        .replace("[","")
//                        .replace("]","")
//                        //.replace(" ","")
//                    this.addHeader("Set-Cookie", cookiesStr)
//                    Log.e("ZRC1", cookiesStr)
//                    this
//                }
//                it.proceed(builder.build())
//            }
//            .setInterceptor {
//                val resp = it.proceed(it.request())
//                val cookies = resp.headers("Set-Cookie")
//                HawkSpUtitls.save("cookie", cookies)
//                Log.e("ZRC0", GsonUtils.toJson(cookies))
//                resp
//            }
            .build()//设置完，记得Buid
    }

    private fun initSmartRefreshLayout() {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator { context, layout ->
            layout.setPrimaryColorsId(R.color.white, R.color.gray_8a8a8a) //全局设置主题颜色
            ClassicsHeader(context)
        }
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator { context, layout ->
            layout.setPrimaryColorsId(R.color.white, R.color.gray_8a8a8a)
            ClassicsFooter(context).setDrawableSize(20f)//指定为经典Footer
        }
    }

    override fun onTerminate() {
        super.onTerminate()
        Net.destroy()
    }
}